// 用户端动态图库加载脚本
class DynamicGalleryLoader {
    constructor() {
        this.galleryAPI = window.userGalleryAPI;
        this.init();
    }

    async init() {
        try {
            // 并行加载所有图片资源
            await Promise.all([
                this.loadCarouselImages(),
                this.loadSiteLogo(),
                this.loadFavicon()
            ]);
            
            console.log('图库资源加载完成');
        } catch (error) {
            console.error('图库资源加载失败:', error);
        }
    }

    // 加载轮播图
    async loadCarouselImages() {
        try {
            const carouselImages = await this.galleryAPI.getActiveCarouselImages();
            this.renderCarousel(carouselImages);
        } catch (error) {
            console.error('加载轮播图失败:', error);
            this.renderDefaultCarousel();
        }
    }

    // 渲染轮播图
    renderCarousel(images) {
        const carouselInner = document.getElementById('carouselInner');
        if (!carouselInner || !images || images.length === 0) {
            this.renderDefaultCarousel();
            return;
        }

        let carouselHTML = '';
        images.forEach((image, index) => {
            const isActive = index === 0 ? 'active' : '';
            carouselHTML += `
                <div class="carousel-item ${isActive}">
                    <img src="${image.imageUrl}" alt="${image.name}" loading="lazy">
                    <div class="carousel-caption">
                        <h2>${image.title || image.name}</h2>
                        <p>${image.description || ''}</p>
                        ${image.link ? `<a href="${image.link}" class="btn">${image.buttonText || '了解更多'}</a>` : ''}
                    </div>
                </div>
            `;
        });

        carouselInner.innerHTML = carouselHTML;
        
        // 重新初始化轮播图
        this.reinitializeCarousel();
    }

    // 渲染默认轮播图
    renderDefaultCarousel() {
        const carouselInner = document.getElementById('carouselInner');
        if (!carouselInner) return;

        const defaultHTML = `
            <div class="carousel-item active">
                <img src="/static/tp/2a8ff2dc-e9ef-426d-b1e8-a0fe7470a1a2.jpg" alt="品质骑行">
                <div class="carousel-caption">
                    <h2>品质骑行，全球直达</h2>
                    <p>严选自行车、电动车及滑板车，匠心打造品质，支持全球配送，售后无忧。</p>
                    <a href="/products" class="btn">查看产品</a>
                </div>
            </div>
            <div class="carousel-item">
                <img src="/static/tp/6b3cd5f7-f8d7-4c54-babe-5a0b74450e4a.jpg" alt="ubike">
                <div class="carousel-caption">
                    <h2>ubike</h2>
                    <p>我们是ubike，就想让你买到省心的骑行装备！</p>
                    <a href="/about" class="btn">了解我们</a>
                </div>
            </div>
            <div class="carousel-item">
                <img src="/static/tp/43ab696e-5269-44c4-aa9e-1900812219b3.jpg" alt="专业服务">
                <div class="carousel-caption">
                    <h2>专业服务团队</h2>
                    <p>专业团队，为您提供最优质的服务</p>
                    <a href="/contact" class="btn">联系我们</a>
                </div>
            </div>
        `;

        carouselInner.innerHTML = defaultHTML;
        this.reinitializeCarousel();
    }

    // 重新初始化轮播图
    reinitializeCarousel() {
        // 重置轮播图状态
        if (typeof initSlider === 'function') {
            initSlider();
        }
        
        // 重新绑定控制事件
        if (typeof bindCarouselControls === 'function') {
            bindCarouselControls();
        }
    }

    // 加载网站Logo
    async loadSiteLogo() {
        try {
            const logo = await this.galleryAPI.getCurrentLogo();
            this.renderSiteLogo(logo);
        } catch (error) {
            console.error('加载Logo失败:', error);
            this.renderDefaultLogo();
        }
    }

    // 渲染网站Logo
    renderSiteLogo(logo) {
        const logoImg = document.getElementById('siteLogo');
        if (!logoImg || !logo) {
            this.renderDefaultLogo();
            return;
        }

        logoImg.src = logo.imageUrl;
        logoImg.alt = logo.alt || logo.name;
        logoImg.title = logo.name;
    }

    // 渲染默认Logo
    renderDefaultLogo() {
        const logoImg = document.getElementById('siteLogo');
        if (logoImg) {
            logoImg.src = '/static/tp/Logo.png';
            logoImg.alt = 'ubike';
        }
    }

    // 加载网站图标
    async loadFavicon() {
        try {
            const logo = await this.galleryAPI.getCurrentLogo();
            if (logo && logo.imageUrl) {
                this.updateFavicon(logo.imageUrl);
            }
        } catch (error) {
            console.error('加载网站图标失败:', error);
        }
    }

    // 更新网站图标
    updateFavicon(iconUrl) {
        // 移除现有的favicon
        const existingFavicon = document.querySelector('link[rel="icon"], link[rel="shortcut icon"]');
        if (existingFavicon) {
            existingFavicon.remove();
        }

        // 创建新的favicon链接
        const favicon = document.createElement('link');
        favicon.rel = 'icon';
        favicon.href = iconUrl;
        favicon.type = 'image/x-icon';
        
        document.head.appendChild(favicon);
    }

    // 加载产品图片（用于产品页面）
    async loadProductImages(productId, containerId) {
        try {
            const images = await this.galleryAPI.getProductImages(productId);
            this.renderProductImages(images, containerId);
        } catch (error) {
            console.error('加载产品图片失败:', error);
        }
    }

    // 渲染产品图片
    renderProductImages(images, containerId) {
        const container = document.getElementById(containerId);
        if (!container || !images || images.length === 0) return;

        let imagesHTML = '';
        images.forEach((image, index) => {
            const isMain = image.isMain ? 'main-image' : '';
            imagesHTML += `
                <div class="product-image ${isMain}" data-image-id="${image.id}">
                    <img src="${image.imageUrl}" alt="${image.name}" loading="lazy">
                    ${image.isMain ? '<span class="main-badge">主图</span>' : ''}
                </div>
            `;
        });

        container.innerHTML = imagesHTML;
    }

    // 加载博客封面图（用于博客页面）
    async loadBlogCoverImage(blogId, imgElementId) {
        try {
            const coverImage = await this.galleryAPI.getBlogCoverImage(blogId);
            this.renderBlogCoverImage(coverImage, imgElementId);
        } catch (error) {
            console.error('加载博客封面图失败:', error);
        }
    }

    // 渲染博客封面图
    renderBlogCoverImage(coverImage, imgElementId) {
        const imgElement = document.getElementById(imgElementId);
        if (!imgElement || !coverImage) return;

        imgElement.src = coverImage.imageUrl;
        imgElement.alt = coverImage.name || '博客封面图';
        imgElement.title = coverImage.name;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 等待图库API加载完成
    if (typeof window.userGalleryAPI !== 'undefined') {
        window.dynamicGalleryLoader = new DynamicGalleryLoader();
    } else {
        // 如果API未加载，延迟初始化
        setTimeout(() => {
            if (typeof window.userGalleryAPI !== 'undefined') {
                window.dynamicGalleryLoader = new DynamicGalleryLoader();
            } else {
                console.warn('图库API未加载，使用默认图片');
                // 手动创建默认加载器
                const loader = new DynamicGalleryLoader();
                loader.renderDefaultCarousel();
                loader.renderDefaultLogo();
            }
        }, 1000);
    }
});